﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MachineBuildingSystem
{
    public partial class RegistrationFeeAddForm : XtraForm
    {
        private long m_SaleOutId = -1;
        public long SaleOutId
        {
            set { m_SaleOutId = value; }
            get { return m_SaleOutId; }
        }

        private OrderInfo m_SaleOrder = new OrderInfo();
        public OrderInfo SaleOrder
        {
            set { m_SaleOrder = value; }
            get { return m_SaleOrder; }
        }

        private string m_CurrentUser = "";
        public string CurrentUser
        {
            set { m_CurrentUser = value; }
        }
        private string m_Password = "";
        public string Password
        {
            set { m_Password = value; }
        }

        private string m_CarCode = "";
        public string CarCode
        {
            set { m_CarCode = value; }
            get { return m_CarCode; }
        }

        private string m_Driver = "";
        public string Driver
        {
            set { m_Driver = value; }
            get { return m_Driver; }
        }

        private DateTime m_DeliDate = DateTime.MinValue;
        public DateTime DeliDate
        {
            set { m_DeliDate = value; }
            get { return m_DeliDate; }
        }

        private List<ExpenseTypeData> m_ExpenseTypeDataList = new List<ExpenseTypeData> ();
        public List<ExpenseTypeData> ExpenseTypeDataList
        {
            set { m_ExpenseTypeDataList = value; }
        }
        //选择的费用类别ID
        private long m_SelectedExpenseTypeId = -1;
        public RegistrationFeeAddForm()
        {
            InitializeComponent();
        }

        private void RegistrationFeeAddForm_Load(object sender, EventArgs e)
        {
            InitMruEditCarCode();
            InitMruEditDriver();
            InitMruEditExpenseType();
            dateEditFee.EditValue = m_DeliDate == DateTime.MinValue ? m_SaleOrder.orderDate : m_DeliDate;
            mruEditCarCode.Text = m_CarCode;
            mruEditDriver.Text = m_Driver;
        }

        //初始化司机下拉框
        private void InitMruEditDriver()
        {
            try
            {
                mruEditDriver.Properties.Items.Clear();
                string haveDriverStr = ConfigurationManager.AppSettings["Drivers"];
                foreach (string driver in haveDriverStr.Split(','))
                    mruEditDriver.Properties.Items.Add(driver);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化司机下拉框数据异常：" + ex.Message);
            }
        }

        private void InitMruEditCarCode()
        {
            try
            {
                mruEditCarCode.Properties.Items.Clear();
                string carCodeStr = ConfigurationManager.AppSettings["CarCodeStr"];
                foreach (string carCode in carCodeStr.Split(','))
                    mruEditCarCode.Properties.Items.Add(carCode);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化车牌号下拉框数据异常：" + ex.Message);
            }
        }

        //初始化费用类别下拉框
        private void InitMruEditExpenseType()
        {
            try
            {
                if (m_ExpenseTypeDataList == null || m_ExpenseTypeDataList.Count == 0)
                    return;
                mruEditExpenseType.Properties.Items.Clear();
                foreach (ExpenseTypeData expenseType in m_ExpenseTypeDataList)
                {
                    DataInfo data = new DataInfo();
                    data.Id = expenseType.id;
                    data.Value = expenseType.names;
                    mruEditExpenseType.Properties.Items.Add(data);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化费用类别下拉框异常：" + ex.Message);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (m_SaleOutId <= 0 && rgpRegistrationType.SelectedIndex == 0)
            {
                MessageBox.Show(this, "无发货单，不能新增单车费用！");
                return;
            }
            if (m_SelectedExpenseTypeId <= 0)
            {
                MessageBox.Show(this, "请选择费用类别！");
                this.mruEditExpenseType.Focus();
                return;
            }
            //if (Convert.ToDecimal(spinEditNumber.EditValue) <= 0)
            //{
            //    MessageBox.Show(this, "数量不能小于等于0！");
            //    this.spinEditNumber.Focus();
            //    return;
            //}
            //if (Convert.ToDecimal(spinEditPrice.EditValue) <= 0)
            //{
            //    MessageBox.Show(this, "单价不能小于等于0！");
            //    this.spinEditPrice.Focus();
            //    return;
            //}
            try
            {
                List<Dictionary<string, object>> list = GetDeliverySaveData();
                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(list);
                if (!DataHelper.SaveSaleExpenses(m_CurrentUser, m_Password))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "保存失败:" + ex.Message);
                return;
            }
            MessageBox.Show(this, "保存成功");
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private List<Dictionary<string, object>> GetDeliverySaveData()
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("customerId", m_SaleOrder.customerId);
            dic.Add("belongcorpId", m_SaleOrder.corpId);
            //若是单车费用，则传入出库单ID，若是整单费用，则将其销售ID保存
            dic.Add("saleOrderId", m_SaleOrder.id);
            if (rgpRegistrationType.SelectedIndex == 0)
                dic.Add("saleOutLineId", m_SaleOutId);
            dic.Add("expenseDate", ((DateTime)dateEditFee.EditValue).ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("expenseName", this.mruEditExpenseType.Text.Trim());

            string expenseType = "";
            //根据费用名称获取费用类型
            var query = from temp in m_ExpenseTypeDataList
                        where temp.names == this.mruEditExpenseType.Text.Trim()
                        select temp;
            if (query.Count() >= 1)
                expenseType = query.ToList<ExpenseTypeData>()[0].types;
            dic.Add("expenseType", expenseType);

            decimal quantity = Convert.ToDecimal(spinEditNumber.EditValue);
            decimal price = Convert.ToDecimal(spinEditPrice.EditValue);
            dic.Add("quantity", quantity);
            dic.Add("price", price);
            dic.Add("moneys", quantity * price);
            dic.Add("remarks", this.txtRemarks.Text.Trim());
            dic.Add("carCode", mruEditCarCode.Text.Trim());
            dic.Add("driverName", mruEditDriver.Text.Trim());
            list.Add(dic);
            return list;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void mruEditExpenseType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mruEditExpenseType.SelectedItem == null || mruEditExpenseType.SelectedItem == "")
                m_SelectedExpenseTypeId = -1;
            else
            {
                if (mruEditExpenseType.SelectedItem as DataInfo != null)
                    m_SelectedExpenseTypeId = ((DataInfo)mruEditExpenseType.SelectedItem).Id;
                else
                    m_SelectedExpenseTypeId = -1;
            }
        }

        private void rgpRegistrationType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //整单费用需传日期
            if (rgpRegistrationType.SelectedIndex == 0)
            {
                //费用添加单车费用时，默认发货时间
                if(m_DeliDate != DateTime.MinValue)
                    dateEditFee.EditValue = m_DeliDate;
                else
                    dateEditFee.EditValue = m_SaleOrder.orderDate;
                mruEditCarCode.Text = m_CarCode;
                mruEditDriver.Text = m_Driver;
            }
            else
            {
                dateEditFee.EditValue = m_SaleOrder.productDate;
                mruEditCarCode.Text = "";
                mruEditDriver.Text = "";
            }
        }

        private void spinEditNumber_EditValueChanged(object sender, EventArgs e)
        {
            decimal quantity = Convert.ToDecimal(spinEditNumber.EditValue);
            decimal price = Convert.ToDecimal(spinEditPrice.EditValue);
            txtMoney.Text = (quantity * price).ToString();
        }

        private void spinEditPrice_EditValueChanged(object sender, EventArgs e)
        {
            decimal quantity = Convert.ToDecimal(spinEditNumber.EditValue);
            decimal price = Convert.ToDecimal(spinEditPrice.EditValue);
            txtMoney.Text = (quantity * price).ToString();
        }
    }
}
